export default class Mask {
    /**
     * @type {Function[]}
     */
    closeFunctionList = [];

    /**
     * @type {Function | null}
     */
    onceCallback = null;

    constructor() {
        this.mask = document.createElement("div");
        this.mask.className = "mask";
        this.mask.style.display = "none";
        this.mask.style.position = "fixed";
        this.mask.style.top = "0";
        this.mask.style.left = "0";
        this.mask.style.width = "100%";
        this.mask.style.height = "100%";
        this.mask.style.backgroundColor = "rgba(0, 0, 0, 0.1)";
        this.mask.style.zIndex = "999";

        document.body.appendChild(this.mask);
        this.mask.onclick = () => {
            this.hide();
        };
    }
    addCloseFunction(f) {
        this.closeFunctionList.push(f);
        return this;
    }
    removeCloseFunction(f) {
        const idx = this.closeFunctionList.indexOf(f);
        if (idx != -1) {
            this.closeFunctionList.splice(idx, 1);
        }
    }
    /**
     * @param {Function | null} callback
     */
    show(callback = null) {
        this.mask.style.display = "block";
        this.onceCallback = callback;
    }
    /**
     *
     */
    hide() {
        this.mask.style.display = "none";
        this.closeFunctionList.forEach((f) => {
            f();
        });
        if (this.onceCallback) {
            this.onceCallback();
            this.onceCallback = null;
        }
    }
}

var __mask = null;

/**
 * @type {Mask}
 * @param {Function | null} callback
 */
export function Mask_Show(callback = null) {
    if (__mask == null) {
        __mask = new Mask();
    }
    __mask.show(callback);
    return __mask;
}

export function Mask_AddCloseFunction(f) {
    if (__mask == null) {
        __mask = new Mask();
    }
    if (__mask != null) {
        __mask.addCloseFunction(f);
    }
}

export function Mask_Hide() {
    if (__mask == null) {
        __mask = new Mask();
    }
    if (__mask != null) {
        __mask.hide();
    }
}
